<?php
/**
 * Created by PhpStorm.
 * User: win7
 * Date: 2018/7/4 0004
 * Time: 10:02
 */

namespace Wx\Controller;

use Think\Model;
use Wx\Model\ExchangeQrcodeModel;
use Wx\Model\shareModel;

class ExchangeController extends CommonController
{
    public function _initialize(){
        parent::_initialize();

        //获取支付截止时间
        $order_info = M("exchange_order")->where("state = 0")->select();//获取所有订单记录

        foreach($order_info as $pk => $pv){
            $deadline = strtotime(date('YmdHis',$pv['addtime'])." +1 hours")-time();
            $deadline = $deadline>0?$deadline:0;

            //支付状态更改
            if($deadline == 0){
                M("exchange_order")->where("id = {$pv['id']} AND state = 0")->save(['state'=>4]);//已失效
                M("exchange_goods")->where("id = {$pv['g_id']}")->setInc('num',1);//退还库存
            }//end if
        }//end foreach

    }//end fun

    //商品详情页
    public function index(){
        $gid = $_GET['gid'];//商品id
        $focus = session("focus");//关注
        if($gid){
            $goods = M("exchange_goods")->where("id = {$gid}")->find();//商品信息
            $goods['head_img'] = explode(',',$goods['head_img']);//图片处理
            $goods['con_img'] = explode(',',$goods['con_img']);//图片处理

            //处理会员价
            if($goods["level_cash_1"] != 0 || $goods["level_integral_1"] != 0){
                $goods['get_price']['普通会员']["level_cash"] = $goods["level_cash_1"];
                $goods['get_price']['普通会员']["level_integral"] = $goods["level_integral_1"];
                unset($goods["level_cash_1"]);
                unset($goods["level_integral_1"]);
            }//end if
            if($goods["level_cash_2"] != 0 || $goods["level_integral_2"] != 0){
                $goods['get_price']['黄金会员']["level_cash"] = $goods["level_cash_2"];
                $goods['get_price']['黄金会员']["level_integral"] = $goods["level_integral_2"];
                unset($goods["level_cash_2"]);
                unset($goods["level_integral_2"]);
            }//end if
            if($goods["level_cash_3"] != 0 || $goods["level_integral_3"] != 0){
                $goods['get_price']['白金会员']["level_cash"] = $goods["level_cash_3"];
                $goods['get_price']['白金会员']["level_integral"] = $goods["level_integral_3"];
                unset($goods["level_cash_3"]);
                unset($goods["level_integral_3"]);
            }//end if
            if($goods["level_cash_4"] != 0 || $goods["level_integral_4"] != 0){
                $goods['get_price']['钻石会员']["level_cash"] = $goods["level_cash_4"];
                $goods['get_price']['钻石会员']["level_integral"] = $goods["level_integral_4"];
                unset($goods["level_cash_4"]);
                unset($goods["level_integral_4"]);
            }//end if

            //微信分享-start
            $wxshare=new shareModel(C('WX_API.appid'),C('WX_API.secret'));
            $signPackage=$wxshare->getSignPackage();
            /*
            *
            array(6) {
              ["appId"] => string(18) "wx6a0daaedc4d00100"
              ["nonceStr"] => string(16) "5cKMHQADQTbRkv2f"
              ["timestamp"] => int(1527576256)
              ["url"] => string(59) "http://www.xiangtws.com/index.php/Wx/Prodetail/index/id/20/"
              ["signature"] => string(40) "a70ef78304bc4f5558439b65955119806e4fb3fe"
              ["rawString"] => string(205) "jsapi_ticket=HoagFKDcsGMVCIY2vOjf9raVdUJqZ1stwmkyXwhMyovuJhCTHjtpRnNxRJSVQ0UacAdrqz97vWdzjRU3Dp-YYw&noncestr=5cKMHQADQTbRkv2f*tamp=1527576256&url=http://www.xiangtws.com/index.php/Wx/Prodetail/index/id/20/"
            }
            *
            */
            $this->assign('signPackage',$signPackage);//微信数据
            //微信分享-end

            //回转URL
            session("pro_url",$_SERVER['REQUEST_URI']);
            $this->assign("focus",$focus);
            $this->assign("goods",$goods);
            $this->display("prodetail-dh");
//            dump($goods);
        }else{
            $this->error("参数不全！");
        }//end if

    }//end fun index()

    //用户权限检测
    public function detection(){
        $gid = $_POST['gid'];//商品id
        $goods = M("exchange_goods")->where("id = {$gid}")->find();//商品信息
        $member = getMember(session('u_id'));//用户信息

        //啤酒或洗衣液的购物限制
        if($gid == 32 || $gid == 33){
            $order_one = M("exchange_order")->where("u_id = {$member['id']} AND g_id in(32,33) AND state != 4")->count('id');//获取限制商品的订单总数
            if($order_one>0){
                $this->ajaxReturn(['info'=>'已兑换，无法再次进行兑换。'],"JSON");return;
            }//end if
        }//end if

        //用户信息检测
        if($member['c_id'] == 0 || empty($member['mobile']) || empty($member['realname']) || $member['hometown'] == NULL){
            $this->ajaxReturn(['info'=>'个人信息未完善，无法进行兑换。','url'=>U("Authentication/index")],"JSON");return;
        }//end if

        //地区检测
        if($goods['u_id'] > 0){
            //门店商品
            $store_c_id = M("shop_store")->where("u_id = {$goods['u_id']}")->getField("c_id");//门店小区
            if ($store_c_id != $member['c_id']){
                $this->ajaxReturn(['info'=>'您不是该小区用户，不能进行兑换。'],"JSON");return;
            }//end if
        }else{
            //品牌商品
            $c_id = explode(',',$goods['c_id_str']);//小区
            if(!in_array($member['c_id'],$c_id)){
                $this->ajaxReturn(['info'=>'您不是该小区用户，不能进行兑换。'],"JSON");return;
            }//end if
        }//end if

        //库存检测
        if ($goods['num'] == 0){
            $this->ajaxReturn(['info'=>'货物已售罄！','url'=>U("Index/index")],"JSON");return;
        }//end if

        //积分检测
        if ($member['growth'] > 6000){
            //钻石会员
            if($goods["level_cash_4"] != 0 || $goods["level_integral_4"] != 0){
                if ($goods["level_integral_4"]){
                    if ($goods["level_integral_4"] > $member['credit1']){
                        $this->ajaxReturn(['info'=>'对不起您的积分不足，无法兑换','url'=>U("Index/index")],"JSON");return;
                    }//end if
                }//end if
            }else{
                $this->ajaxReturn(['info'=>'该商品为指定会员级别兑换','url'=>U("Index/index")],"JSON");return;
            }//end if
        }elseif ($member['growth'] > 3000){
            //白金会员
            if($goods["level_cash_3"] != 0 || $goods["level_integral_3"] != 0){
                if ($goods["level_integral_3"]){
                    if ($goods["level_integral_3"] > $member['credit1']){
                        $this->ajaxReturn(['info'=>'对不起您的积分不足，无法兑换','url'=>U("Index/index")],"JSON");return;
                    }//end if
                }//end if
            }else{
                $this->ajaxReturn(['info'=>'该商品为指定会员级别兑换','url'=>U("Index/index")],"JSON");return;
            }//end if
        }elseif ($member['growth'] > 1000){
            //黄金会员
            if($goods["level_cash_2"] != 0 || $goods["level_integral_2"] != 0){
                if ($goods["level_integral_2"]){
                    if ($goods["level_integral_2"] > $member['credit1']){
                        $this->ajaxReturn(['info'=>'对不起您的积分不足，无法兑换','url'=>U("Index/index")],"JSON");return;
                    }//end if
                }//end if
            }else{
                $this->ajaxReturn(['info'=>'该商品为指定会员级别兑换','url'=>U("Index/index")],"JSON");return;
            }//end if
        }else{
            //普通会员
            if($goods["level_cash_1"] != 0 || $goods["level_integral_1"] != 0){
                if ($goods["level_integral_1"]){
                    if ($goods["level_integral_1"] > $member['credit1']){
                        $this->ajaxReturn(['info'=>'对不起您的积分不足，无法兑换','url'=>U("Index/index")],"JSON");return;
                    }//end if
                }//end if
            }else{
                $this->ajaxReturn(['info'=>'该商品为指定会员级别兑换','url'=>U("Index/index")],"JSON");return;
            }//end if
        }//end if

    }//end fun detection()

    //订单页
    public function order(){
        $member = getMember(session('u_id'));//用户信息
        $u_c_id = M("member")->where("id = ".session('u_id'))->getField('c_id');//用户小区id
        $store = M("shop_store")->where("c_id = {$u_c_id}")->field("c_id,realname,mobile,address,storename")->find();//门店信息
        $goods = M("exchange_goods")->where("id = {$_GET['gid']}")->find();//商品信息

        if ($member['growth'] > 6000){
            //钻石会员
            if($goods["level_cash_4"] != 0 || $goods["level_integral_4"] != 0){
                $goods["level_cash"] = $goods["level_cash_4"];
                $goods["level_integral"] = $goods["level_integral_4"];
            }//end if
        }elseif ($member['growth'] > 3000){
            //白金会员
            if($goods["level_cash_3"] != 0 || $goods["level_integral_3"] != 0){
                $goods["level_cash"] = $goods["level_cash_3"];
                $goods["level_integral"] = $goods["level_integral_3"];
            }//end if
        }elseif ($member['growth'] > 1000){
            //黄金会员
            if($goods["level_cash_2"] != 0 || $goods["level_integral_2"] != 0){
                $goods["level_cash"] = $goods["level_cash_2"];
                $goods["level_integral"] = $goods["level_integral_2"];
            }//end if
        }else{
            //普通会员
            if($goods["level_cash_1"] != 0 || $goods["level_integral_1"] != 0){
                $goods["level_cash"] = $goods["level_cash_1"];
                $goods["level_integral"] = $goods["level_integral_1"];
            }//end if
        }//end if

        $this->assign('store',$store);
        $this->assign('goods',$goods);
        $this->display("confirmorder-dh");
//        dump($goods);
    }//end fun order()

    //生成订单
    public function addorder(){
        $goods = M("exchange_goods")->where("id = {$_POST['gid']} AND state = 1")->find();//商品信息
        if(!isset($goods)){
            $this->ajaxReturn(['state'=>1,"val"=>'该商品不存在或已下架！'],"JSON");return;
        }//end if
        if($goods['num'] == 0){
            $this->ajaxReturn(['state'=>1,"val"=>'你来晚了，货物已售罄！'],"JSON");return;
        }//end if

        $order_sn = 'JF'.date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);       //生成订单号
        $qrcode = D("ExchangeQrcode")->receive($order_sn);
        $order = array(
            "u_id" => session('u_id'),
            "g_id" => $_POST['gid'],
            "c_id" => $_POST['cid'],
            "total_fee" => $_POST['total_fee'],
            "level_integral" => $_POST['level_integral'],
            "order_sn" => $order_sn,
            "qrcode" => $qrcode,
            "addtime" => time()
        );
        $addorder = M("exchange_order")->add($order);
        if ($addorder){
            M("exchange_goods")->where("id = {$_POST['gid']}")->setDec('num',1);//减库存
            $this->ajaxReturn(['state'=>0,'id'=>$addorder],"JSON");
        }else{
            $this->ajaxReturn(['state'=>1,"val"=>'提交订单失败！'],"JSON");return;
        }//end if
    }//end fun


    //选择支付
    public function choosePay(){
        $order = M("exchange_order")->where("id = ".$_GET['oid']." AND state = 0")->find();//订单信息
        if($order){
            $member = getMember(session('u_id'));//用户信息

            //支付截止时间
            $order['endtime'] = strtotime(date('YmdHis',$order['addtime'])." +1 hours")-time();//截止剩余时间
            $order['endtime'] = $order['endtime'] > 0 ? $order['endtime'] : 0;

            //超时处理
            if($order['endtime'] == 0){
                M("exchange_order")->where("id = ".$_GET['oid']." AND state = 0")->save(['state'=>4]);//订单失效
            }//end if

            $this->assign("member",$member);
            $this->assign("order",$order);
        }else{
            if($order['state'] == 4){
                $this->error("超过截止时间，已失效",U("User/index"));return;
            }else{
                $this->error("非法操作",U("User/index"));return;
            }//end if
        }//end if
        $this->display("pre-pay");
    }//end fun

    //纯积分支付
    public function credit(){
        $order = M("exchange_order")->where("id = ".$_POST['id']." AND state = 0")->find();//订单信息
        $editorder = M("exchange_order")->where("id = ".$_POST['id']." AND state = 0")->save(['state'=>1]);//已付款
        if($editorder){
//            $s_u_id = M("shop_store")->where("c_id = {$order['c_id']}")->getField('u_id');//店铺id
            $credit = M("member")->where("id = {$order['u_id']}")->setDec('credit1',$order['level_integral']);//减积分
            if($credit){

                changeCredit($order['u_id'],"积分兑换",'credit1','-',$order['level_integral']);   //增加积分变动记录
                sendVoice($order['u_id'],'积分兑换共消费：'.$order['level_integral']."积分");   //增加卡额变动记录
                $this->ajaxReturn(['state'=>0],"JSON");
            }else{
                $this->ajaxReturn(['state'=>1,'val'=>"支付失败"],"JSON");
            }//end if
        }else{
            $this->ajaxReturn(['state'=>1,'val'=>"支付失败"],"JSON");
        }//end if
    }//end if

}//end class